<template>
  <div class="body">
    <div class="upper-container">
      <!-- 唱片背景 -->
      <div class="record-container">
        <div class="record-bg">
          <div id="record-img" class="rotate-play"></div>
        </div>
      </div>
      <!-- 音乐介绍 -->
      <div class="introduction-container">
        <div class="text-container">
          <div id="music-title">{{music.name}}</div>
          <div class="author-container">歌手：
            <span id="author-name">{{music.artist}}</span>
          </div>
          <div class="author-container">类型：
            <span id="author-name">{{this.getArtistTypeText(music.artistType)}}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 音乐播放器主要内容 -->
    <div class="audio-box">
      <div class="audio-container">
        <audio ref="audioTag"></audio>
        <!-- 进度条 -->
        <div class="a-progress" @mousedown="seekProgress">
          <div class="pgs-total" ref="progressTotal">
            <div class="pgs-play" id="progress" :style="{width: progress + '%'}"></div>
          </div>
        </div>
        <!-- 下排控制按钮 -->
        <div class="a-controls">
          <!-- 播放时长 -->
          <div class="time-container">
            <span class="played-time" id="playedTime">{{ playedTime }}</span>&nbsp;/&nbsp;
            <span class="audio-time" id="audioTime">{{ audioTime }}</span>
          </div>
          <!-- 中间按钮 -->
          <div class="center-button-container">
            <!-- 播放模式 -->
            <div id="playMode" class="center-icon mode" @click="changePlayMode"></div>
            <!-- 上一首 -->
            <div id="skipForward" class="center-icon s-right" @click="skipForward"></div>
            <!-- 暂停按钮 -->
            <div id="playPause" :class="{ 'icon-pause': isPlaying===true, 'icon-play': isPlaying===false }"  @click="PlayOrPause"></div>
            <!-- 下一首 -->
            <div id="skipBackward" class="center-icon s-left" @click="skipBackward"></div>
            <!-- 音量调节 -->
            <div id="volume" class="center-icon volume"></div>
            <!-- 音量悬浮窗 -->
<!--            <input type="range" id="volumn-togger" name="change" value="70" min="0" max="100" step="1">-->
            <!-- 音量调节滑块 -->
            <input type="range" id="volume-toggler"  name="change" min="0" max="100" step="1" v-model="volume" @input="updateVolume" />
          </div>
          <!-- 后部按钮 -->
          <div class="bottom-button-container">
            <!-- 列表 -->
            <div @click="toggleList" id="list" class="bottom-icon list"></div>
            <!-- 倍速 -->
            <div id="speed" class="speed">1.0X</div>
            <!-- MV -->
            <div id="MV" class="bottom-icon MV"></div>
          </div>
        </div>
      </div>
    </div>

    <div class="music-list" id="music-list" v-show="isOpen">
      <div class="music-list-container">
        <div class="music-list-title">播放队列</div>
        <hr class="line">
        <div style="margin-top: 10px;margin-bottom: 10px">
          <el-input v-model="pagination.name" style="width: 170px;margin-left: 10px" placeholder="歌曲名称" size="mini"></el-input>
          <el-autocomplete
            class="inline-input"
            v-model="pagination.artist"
            :fetch-suggestions="querySearch"
            placeholder="歌手名称"
            :trigger-on-focus="false"
            style="width: 110px;margin-left: 10px;margin-bottom: 10px"
            size="mini"
            @select="handleSelect"
          ></el-autocomplete>

          <el-select clearable v-model="pagination.artistType" placeholder="请选择歌手类型"  style="margin-left: 10px;width: 170px" size="mini">
            <el-option key="1" label="华语男歌手" :value="0"></el-option>
            <el-option key="2" label="华语女歌手" :value="1"></el-option>
            <el-option key="3" label="中国组合" :value="2"></el-option>
            <el-option key="4" label="日韩男歌手" :value="3"></el-option>
            <el-option key="5" label="日韩女歌手" :value="4"></el-option>
            <el-option key="6" label="欧美歌手" :value="5"></el-option>
            <el-option key="7" label="外国组合" :value="6"></el-option>
          </el-select>
          <el-button type="warning" icon="el-icon-refresh" style="margin-left: 10px" size="mini" @click="refresh"></el-button>
          <el-button type="primary" icon="el-icon-search" style="margin-left: 22px" @click="search" size="mini"></el-button>
        </div>
        <hr class="line">
          <el-table :data="musicList"  @cell-mouse-enter="handleMouseEnter"
                    @cell-mouse-leave="handleMouseLeave" @row-click="selectSong"
                    :header-cell-style="{background:'#1d2528',color:'white'}"
                    :cell-style="cellStyle" :show-header="false"
                    >
            <el-table-column prop="name"></el-table-column>
            <el-table-column prop="artist"></el-table-column>
          </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import artists from '../assets/js/artists';
  export default {
    components: {
    },

    data() {
      return {
        music: {
          name: '未知',
          artist: '未知',
          artistType: '未知'
        },
        pagination: {
          name: null,
          artist: null,
          artistType: null
        },
        currentSongIndex: 0,
        isPlaying: false,
        playMode: 1,
        showList: false,
        playbackRate: 1.0,
        volume: 70,
        isMuted: false,
        isOpen: false,
        musicList: [],
        hoverRowIndex: null,
        musicSrc: '',
        progress: 0, // 音乐播放进度
        playedTime: '00:00', // 已播放时间
        audioTime: '00:00', // 总时间
        musicId: '', //当前播放音乐的id
        artistsList: artists,
        listIndex: null,  // 当前musicList的index
        modeId: 1,  // 播放模式：1-顺序播放，2-随机播放

      }
    },

    watch: {},

    created() {
    },

    mounted() {
      document.addEventListener('click', this.handleClickOutside);
      this.$refs.audioTag.addEventListener('timeupdate', this.updateProgress);
      this.$refs.audioTag.addEventListener('ended', this.changePlayMode);
    },
    beforeDestroy() {
      document.removeEventListener('click', this.handleClickOutside);
      this.$refs.audioTag.removeEventListener('timeupdate', this.updateProgress); // 移除事件监听器
      this.$refs.audioTag.removeEventListener('ended', this.changePlayMode);
    },
    computed: {
      // 播放列表鼠标悬停变色
      cellStyle() {
        return (row, column, cellValue) => {
          const rowIndex = this.hoverRowIndex === row.rowIndex;
          return {
            background: rowIndex ? '#3a4c55' : '#1d2528',
            color: 'white',
            'font-size': '15px',
            'text-align': 'center',
            'border-bottom': 'none'
          };
        };
      },
      // 播放模式
    },
    methods: {
      updateVolume() {
        const audio = this.$refs.audioTag;
        audio.volume = this.volume / 100; // 将滑块的值转换为 0 到 1 之间的音量
      },
      seekProgress(event) {
        const audio = this.$refs.audioTag;
        const progressTotal = this.$refs.progressTotal;
        if (!audio.paused || audio.currentTime !== 0) {
          const pgsWidth = parseFloat(window.getComputedStyle(progressTotal, null).width.replace('px', ''));
          const rate = event.offsetX / pgsWidth;
          audio.currentTime = audio.duration * rate;
          this.updateProgress(audio); // 确保这个方法可以访问 audio 对象
        }
      },
      // 修改播放模式： 随机/顺序
      changePlayMode() {
        if (this.modeId === 1) {
          this.listIndex = Math.floor(Math.random() * this.musicList.length);
          this.modeId = 2;
          // 更换图案
          this.$message({
            message: '已切换为随机播放',
            type: 'success'
          });
        } else {
          this.modeId = 1;
          this.$message({
            message: '已切换为顺序播放',
            type: 'success'
          });
        }
      },
      // 刷新
      refresh() {
        this.pagination = {};
        this.search();
      },
      // 搜索
      search() {
        this.$http.post(this.$constant.baseURL + "/play/getMusicList", this.pagination, true)
          .then((res) => {
              this.musicList = res.data.data;
              console.log(this.musicList)
            }
          )
          .catch((error) => {
            this.$message({
              message: error.message,
              type: "error"
            });
          });
      },
      // 搜索提示
      handleSelect() {

      },
      querySearch(queryString, cb) {
        var restaurants = this.artistsList;
        var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (restaurant) => {
          return restaurant.value.toLowerCase().includes(queryString.toLowerCase());
        };
      },
      // 上一首
      skipForward() {
        const index = -- this.listIndex;
        if (index < 0) {
          return ;
        }
        this.selectSong(this.musicList[index])
      },
      // 下一首
      skipBackward() {
        const index = ++ this.listIndex;
        if (index > this.musicList.length) {
          return ;
        }
        this.selectSong(this.musicList[index])
      },
      // 暂停/播放
      PlayOrPause() {
        if (this.isPlaying) {  // 转为暂停
          this.isPlaying = !this.isPlaying;
          this.$refs.audioTag.pause();
          this.stopRotate();
        }else {   // 转为播放
          this.isPlaying = !this.isPlaying;
          this.$refs.audioTag.play();
          this.rotateRecord();
        }
      },
      // 实时更新进度条和播放时间
      updateProgress() {
        const audio = this.$refs.audioTag;
        const value = audio.currentTime / audio.duration;
        this.progress = value * 100; // 更新进度条宽度
        this.playedTime = this.transTime(audio.currentTime); // 更新已播放时间
      },
      // 音频播放时间换算
      formatTime(value) {
        var time = "";
        var s = value.split(':');
        var i = 0;
        for (; i < s.length - 1; i++) {
          time += s[i].length == 1 ? ("0" + s[i]) : s[i];
          time += ":";
        }
        time += s[i].length == 1 ? ("0" + s[i]) : s[i];

        return time;
      },
      transTime(value) {
        var time = "";
        var h = parseInt(value / 3600);
        value %= 3600;
        var m = parseInt(value / 60);
        var s = parseInt(value % 60);
        if (h > 0) {
          time = this.formatTime(h + ":" + m + ":" + s);
        } else {
          time = this.formatTime(m + ":" + s);
        }
        return time;
      },
      //初始化音乐
      initMusic() {
        const audio = this.$refs.audioTag;
        audio.src = this.musicSrc;
        audio.load();
        audio.ondurationchange = () => {
          this.isPlaying = true;
          this.audioTime = this.transTime(audio.duration);
          audio.currentTime = 0;
          this.updateProgress();
        };
      },
      // 播放音乐
      playMusic() {
        const audio = this.$refs.audioTag;
        this.initMusic();
        this.rotateRecord();
        audio.play();
      },
      // 唱片旋转
      rotateRecord() {
        const recordImg = document.getElementById('record-img');
        recordImg.style.animationPlayState = "running";
      },
      // 唱片停止旋转
      stopRotate() {
        const recordImg = document.getElementById('record-img');
        recordImg.style.animationPlayState = "paused";
      },
      // 点击播放列表外部时，关闭播放列表
      isElementInList(element) {
        return document.getElementById('music-list').contains(element) || document.getElementById('list').contains(element);
      },
      handleClickOutside() {
        if (this.isOpen && !this.isElementInList(event.target)) {
          this.isOpen = false;
        }
      },
      // 播放列表鼠标悬停变色 --- Start
      handleMouseLeave() {
        this.hoverRowIndex = null;
      },
      handleMouseEnter(row) {
        this.hoverRowIndex = this.musicList.indexOf(row);
      },
      // 播放列表鼠标悬停变色 --- End
      selectSong(row) {
        this.listIndex =  this.musicList.indexOf(row);
        // 修改封面的信息
        this.music.name = row.name;
        this.music.artist = row.artist;
        this.music.artistType = row.artistType;
        this.musicSrc = row.filePath;
        this.musicId = row.id;
        // 播放
        this.playMusic();
      },
      toggleList() {
        if (this.isOpen === false) {
          this.$http.post(this.$constant.baseURL + "/play/getMusicList", this.pagination, true)
            .then((res) => {
                this.musicList = res.data.data;
                console.log(this.musicList)
              }
            )
            .catch((error) => {
              this.$message({
                message: error.message,
                type: "error"
              });
            });
        }
        this.isOpen = !this.isOpen;
      },
      getArtistTypeText(artistType) {
        switch (artistType) {
          case 0:
            return "华语男歌手";
          case 1:
            return "华语女歌手";
          case 2:
            return "中国组合";
          case 3:
            return "日韩男歌手";
          case 4:
            return "日韩女歌手";
          case 5:
            return "欧美歌手";
          case 6:
            return "外国组合";
          default:
            return "未知";
        }
      },
    }
  }
</script>

<style scoped>



/deep/ .el-input .el-input__inner {
  background-color: rgba(255, 255, 255, 0.1); /* 半透明背景 */
  border: 1px solid #409eff; /* 绿色边框 */
  color: #FFFFFF; /* 白色文本 */
}

/deep/ .el-input .el-input__inner:focus {
  box-shadow: 0 0 0 1px #409eff; /* 聚焦时的阴影效果 */
}

/deep/ .el-table::before {
  height: 0;
}

/deep/ .el-autocomplete .el-input__inner {
  background-color: rgba(255, 255, 255, 0.1); /* 半透明背景 */
  border: 1px solid #409eff; /* 绿色边框 */
  color: #FFFFFF; /* 白色文本 */
}

/deep/ .el-autocomplete .el-input__inner:focus {
  box-shadow: 0 0 0 1px #409eff; /* 聚焦时的阴影效果 */
}

/* 唱片旋转 */
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.record-container .rotate-play {
  animation: rotate 10s linear infinite;
  animation-play-state: paused; /* 初始状态为暂停 */
}
.body {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

html,
.body {
  height: 100%;
  background-size: cover;
  background: url("../assets/img/bg0.png");
  backdrop-filter: blur(50px);
  overflow: hidden;
}


/* 实现唱片效果 */
.record-container {
  margin-top: 100px;
  width: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  float: left;
}

.record-bg {
  background-color: black;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 500px;
  height: 500px;
  border-radius: 500px;
}

#record-img {
  background-image: url("../assets/img/record1.jpg");
  background-size: 100% 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 250px;
  height: 250px;
  border-radius: 250px;
}

.record-center {
  background-color: black;
  width: 20px;
  height: 20px;
  border-radius: 20px;
}

.introduction-container {
  width: 50%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  float: left;
}

.text-container {
  width: 80%;
  padding-left: 20%;
  margin-top: 30%;
}

#music-title {
  color: rgba(255, 255, 255, 0.888);
  font-size: 4rem;
  line-height: 6rem;
}

.author-container {
  color: rgb(171, 171, 171);
  font-size: medium;
}

.audio {
  width: 100%;
}

/* 播放器样式设置*/
.audio-box {
  width: 100%;
  height: 20%;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 设置超出部分隐藏，方便改变图标颜色 */
  overflow: hidden;
}

.audio-container {
  width: 90%;
}

/* 进度条样式 */
.a-progress {
  width: 100%;
  color: #42b680;
  background-color: transparent;
  border-radius: 10px;
  margin-bottom: 10px;
}

.pgs-total {
  width: 100%;
  height: 16px;
  background-color: transparent;
  border-radius: 10px;
  position: relative;
}

.a-progress .pgs-total:after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  top: 7px;
  bottom: 7px;
  background-color: #bbbbbb;
  border-radius: 10px;
  z-index: -1;
}

.a-progress .pgs-total .pgs-play:before {
  content: '';
  position: absolute;
  top: 7px;
  bottom: 7px;
  left: 0;
  right: 0;
  background-color: #42b680;
  border-radius: 10px;
  z-index: 1;
}

.a-progress .pgs-total .pgs-play {
  height: 100%;
  position: relative;
  border-radius: 10px;
}

/* 下排控制按钮样式*/
.a-controls {
  width: 100%;
}

/* 时间样式 */
.time-container {
  width: 30%;
  float: left;
  color: white;
  font-weight: 300;
  line-height: 50px;
}

.played-time {
  left: 15px;
  text-align: left;
}

.audio-time {
  right: 15px;
  text-align: right;
}

/* 中间部分按钮 */
.center-button-container {
  width: 40%;
  float: left;
  display: flex;
  align-items: center;
  justify-content: center;
}

.center-icon {
  float: left;
  width: 30px;
  height: 30px;
  margin-left: 10px;
  margin-right: 10px;
}

.center-icon:hover {
  opacity: 0.7;
}

.center-icon:active {
  opacity: 0.6;
}

.mode {
  background-image: url("../assets/img/mode1.png");
  background-size: 100% 100%;
}

.s-left {
  background-image: url("../assets/img/下一首.png");
  background-size: 100% 100%;
}

.icon-play {
  float: left;
  width: 50px;
  height: 50px;
  background-image: url("../assets/img/继续播放.png");
  background-size: 100% 100%;
}

.icon-pause {
  float: left;
  width: 50px;
  height: 50px;
  background-image: url("../assets/img/暂停.png");
  background-size: 100% 100%;
}

.s-right {
  background-image: url("../assets/img/上一首.png");
  background-size: 100% 100%;
}

.volume {
  background-image: url("../assets/img/音量.png");
  background-size: 100% 100%;
}

/* 尾部按钮 */
.bottom-button-container {
  width: 30%;
  padding-top: 10px;
  float: left;
  text-align: right;
}

.bottom-icon {
  float: right;
  width: 20px;
  height: 20px;
  margin-left: 10px;
  margin-right: 10px;
}

.bottom-icon:hover {
  opacity: 0.7;
}

.bottom-icon:active {
  opacity: 0.6;
}

.MV {
  background-image: url("../assets/img/MV.png");
  background-size: 100% 100%;
}

.speed {
  margin-left: 10px;
  margin-right: 10px;
  float: right;
  font-weight: 300;
  color: white;
}

.speed:hover {
  opacity: 0.7;
  cursor: default;
}

.speed:active {
  opacity: 0.6;
  cursor: default;
}

.list {
  background-image: url("../assets/img/列表.png");
  background-size: 100% 100%;
}

/* 音乐列表 */
.close-list {
  display: none;
  position: fixed;
  height: 100%;
  left: 0;
  top: 0;
  width: 75%;
}

.music-list {
  position: fixed;
  height: 500px;
  right: 0;
  top: 0;
  width: 25%;
  background-color: rgb(29, 37, 40);
  margin-top: 70px;
  margin-right: 100px;
  overflow-y: auto; /* 允许垂直方向上的滚动 */
}

.music-list-container {
  width: 100%;
}

.music-list-title {
  color: white;
  font-size: 2rem;
  font-weight: 300;
  padding: 7.6% 15% 0% 15%;
}

.line {
  height: 1px;
  width: 90%;
  border: none;
  border-top: 1px dashed #4d806b;
}

.all-list div {
  height: 50px;
  line-height: 50px;
  color: white;
  font-weight: 300;
  padding: 0% 15% 0% 15%;
}

.all-list div:hover {
  background-color: rgb(27, 37, 30);
  cursor: default;
}

.list-card-show {
  animation: showAni;
  animation-duration: 1s;
  animation-fill-mode: forwards;
  -webkit-animation-fill-mode: forwards;
}

.list-card-hide {
  animation: hideAni;
  animation-duration: 1s;
  animation-fill-mode: forwards;
  -webkit-animation-fill-mode: forwards;
}

.rotate-play {
  animation: rotateAni 10s infinite linear;
  animation-play-state: paused;
  animation-fill-mode: forwards;
  -webkit-animation-fill-mode: forwards;
}

@keyframes hideAni {
  from {
    transform: translateX(0%);
  }

  to {
    transform: translateX(100%);
  }
}

@keyframes showAni {
  from {
    transform: translateX(100%);
  }

  to {
    transform: translateX(0%);
  }
}

@keyframes rotateAni {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

/*横条样式*/
#volumn-togger {
  width: 100px;
  height: 2px;
  appearance: none;
  background-color: #dcdcdc;
  outline: none;
  overflow: hidden;
  border-radius: 15px;
  box-shadow: inset 0 0 5px rgb(91, 91, 91);
}

/*拖动块的样式*/
#volumn-togger::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 1px;
  height: 5px;
  border-radius: 50%;
  background: #42b680;
  cursor: pointer;
  border: 4px solid #33333300;
  box-shadow: -407px 0 0 400px #42b680;
}
</style>
